import base64

import logger
from django.shortcuts import render

from rest_framework.parsers import JSONParser
from rest_framework.decorators import api_view
from django.http import JsonResponse
from .models import User, Item


# Create your views here.

# 判空的方法
def is_empty(c):
    return c is None or str(c).strip() == ''


# 加密的方法
def b64cencode(c):
    # 把参数转成字节格式
    bc = bytes(c, encoding='utf-8')
    b64c = base64.b64encode(bc).decode('utf-8')
    return b64c


import string, random
from django.core.signing import Signer
from django.core.cache import cache
from datetime import timedelta


# 产生token的方法
def create_token(name):
    # 生成一个8位数的随机字符串
    reqstr = ''.join(random.choices(string.ascii_letters, k=8))
    # 对生成的字符串进行签名 产生token
    token = Signer().sign(reqstr + name)
    # 生成的token放到服务器缓存中
    cache.set(f'test_{name}', token, timeout=timedelta(minutes=100).total_seconds())
    # 返回token
    return token


# 鉴权的方法
def check_token(request):
    # 获取到token
    get_token = request.META.get('HTTP_TOKEN')
    if get_token is None:
        return False, 'token不存在'
    # 对token进行反签名
    untoken = Signer().unsign(get_token)
    # 通过反签名后的token找到name
    name = untoken[8:]
    # 根据name在缓存中找到token
    token = cache.get(f'test_{name}')
    if token is None:
        return False, 'token不存在或已过期'
    return True, name

# 修改物品信息
@api_view(['PUT'])
def update_Item(request,itemid):
    data = JSONParser().parse(request)
    title = data.get('title')
    price = data.get('price')
    seller_id = data.get('seller_id')
    status = data.get('spstatus')
    user_id = data.get('user_id')
    obj = Item.objects.get(id=itemid)
    if is_empty(title)is False:
        obj.title=title
    if is_empty(price)is False:
        obj.price=price
    if is_empty(seller_id)is False:
        obj.seller_id=seller_id
    if is_empty(status)is False:
        obj.status=status
    if is_empty(user_id)is False:
        obj.user_id=user_id
    obj.save()
    return JsonResponse({
        'msg':'修改成功！'
    })

# 删除物品-单删
@api_view(['DELETE'])
def delete_Item(request,itemid):
    obj = Item.objects.get(id=itemid)
    logger.logger.info('aa',itemid)
    obj.delete()
    return JsonResponse({
        'msg':'删除成功！'
    })

# 物品购买后修改状态
@api_view(['POST'])
def buy_Item(request):
    flag,name = check_token(request)
    if flag is False:
        return JsonResponse({
            'msg': '未登录，请先登录！'
        }, status=400)
    data = JSONParser().parse(request)
    item_id = data.get('item_id')
    obj = Item.objects.get(id=item_id)
    if is_empty(item_id) is False:
        obj.status = 'sold'
        return JsonResponse({
            'msg': '修改成功！'
        })
    return JsonResponse({
        'msg':'必填参数为空！'
    },status=400)

# 物品浏览接口
@api_view(['GET'])
def get_available_Item(request):
    allobj = Item.objects.filter()
    lis = []
    for obj in allobj:
        if obj.status == 'available':
            lis.append({
                'id': obj.id,
                'title': obj.title,
                'price': obj.price,
                'seller_id': obj.seller_id,
                'status': obj.status,
                'user_id': obj.user_id_id
            })
    return JsonResponse({
        'msg': '可售物品列表！',
        'data': lis,
        'items': allobj.count()
    })

# 物品发布接口
@api_view(['POST'])
def add_Item(request):
    data = JSONParser().parse(request)
    title = data.get('title')
    price = data.get('price')
    seller_id = data.get('seller_id')
    status = data.get('spstatus')
    user_id = data.get('user_id')
    if is_empty(title) or is_empty(price):
        return JsonResponse({
            'msg': '必填参数为空！'
        }, status=400)
    try:
        Item(title=title, price=price, seller_id=seller_id, status=status, user_id_id=user_id).save()
        # obj = Item.objects.get(title=title)
        # lis = []
        # lis.append({
        #     'title': obj.title,
        #     'price': obj.price,
        #     'seller_id': obj.seller_id,
        #     'status': obj.status,
        #     'user_id': obj.user_id
        # })
        return JsonResponse({
            'msg': '发布成功！',
        })
    except Exception as e:
        return JsonResponse({
            'msg': '发布失败！',
            'data': e
        })

# 用户注册接口
@api_view(['POST'])
def user_register(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    if is_empty(name) or is_empty(password):
        return JsonResponse({
            'msg': '必填参数为空！'
        }, status=400)
    if User.objects.filter(username=name).exists():
        return JsonResponse({
            'msg': '账号已存在！'
        }, status=200)
    # 对密码进行加密存储
    b64cpassword = b64cencode(password)
    User(username=name, password=b64cpassword).save()
    return JsonResponse({
        'msg': '注册成功！'
    })

# 用户登录接口
@api_view(['POST'])
def user_login(request):
    data = JSONParser().parse(request)
    name = data.get('name')
    password = data.get('password')
    if is_empty(name) or is_empty(password):
        return JsonResponse({
            'msg': '必填参数为空！'
        }, status=400)
    # 查看username数据库是否存在
    if User.objects.filter(username=name).exists() is False:
        return JsonResponse({
            'msg': '账号不存在！'
        }, status=404)
    # 对密码进行加密
    b64cpassword = b64cencode(password)
    obj = User.objects.get(username=name, password=b64cpassword)
    # 获取token
    token = create_token(name)
    lis = []
    lis.append({
        'name', obj.username,
        'password', obj.password
    })
    return JsonResponse({
        'msg': '登录成功！',
        'token': token
    })
